const path               = require('path')
const webpack            = require('webpack')
const HtmlWebpackPlugin  = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const ExtractTextPlugin  = require("extract-text-webpack-plugin")


module.exports = env => {
  if(!env){
    env = {}
  }

  let plugins = [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({ template : './app/views/index.html' }),
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ]

  if(env.production){
    plugins.push(
      new webpack.DefinePlugin({
        'process.env' : {
          NODE_ENV : '"production"'
        }
      }),
      new ExtractTextPlugin("style.css", { ignoreOrder : true })
    )
  }

  return {
    // 入口文件，viewport是自适应的js动态计算rem的插件
    entry : ['./app/js/viewport.js', './app/js/main.js'],

    // 出口文件
    output : {
      filename : '[name].min.js',
      path     : path.resolve(__dirname, 'dist')
    },

    // 开发时的hot启动和配置
    devServer : {
      contentBase    : './dist',
      hot            : true,
      compress       : true,
      port           : 9000,
      clientLogLevel : "none",
      quiet          : true
    },

    // 提取模块
    module : {
      loaders : [
        {
          test    : /\.html$/,
          loader  : 'html-loader'
        }, 
        {
          test    : /\.vue$/,
          loader  : 'vue-loader',
          options : {
            // css模块化
            cssModules : {
              localIdentName : '[path][name]---[local]---[hash:base64:5]',
              camelCase      : true  // 驼峰式
            },

            // 提取CSS打包成单独的文件
            extractCSS : true,

            // 解析CSS的loader
            loaders    : env.production
            ? {
              css  : ExtractTextPlugin.extract({
                use      : 'css-loader!px2rem-loader?remUnit=40&remPrecision=8', 
                fallback : 'vue-style-loader'
              }),
              scss : ExtractTextPlugin.extract({
                use      : 'css-loader!px2rem-loader?remUnit=40&remPrecision=8!sass-loader', 
                fallback : 'vue-style-loader'
              })
            }
            : {
              css  : 'vue-style-loader!css-loader!px2rem-loader?remUnit=40&remPrecision=8',
              scss : 'vue-style-loader!css-loader!px2rem-loader?remUnit=40&remPrecision=8!sass-loader'
            }
          }
        }, 
        {
          test    : /\.scss$/,
          loader  : 'style-loader!css-loader!sass-loader'
        }
      ]
    },

    resolve : {
      extensions : ['.js', '.vue', '.json'],
      alias      : {
        'vue$' : 'vue/dist/vue.esm.js'
      }
    },

    // 由上面的变量传递的值
    plugins    
  }
};
